#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h> 
#include"Log.hpp"
#include"Common.hpp"

using namespace LogModule;

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        std::cout<<"Usage: "<<argv[0]<<" <server_ip> <server_port>"<<std::endl;
        return 1;
    }
    std::string server_ip=argv[1];
    int server_port=::atoi(argv[2]);

    int sockfd=::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        std::cout<<"Error in creating socket"<<std::endl;
        return 1;
    }
    struct sockaddr_in client_addr;
    memset(&client_addr,0,sizeof(client_addr));
    client_addr.sin_family=AF_INET;
    client_addr.sin_port=htons(server_port);
    client_addr.sin_addr.s_addr=inet_addr(server_ip.c_str());


    int ret=::connect(sockfd,CONV(&client_addr),sizeof(client_addr));
    if(ret<0)
    {
        std::cout<<"Error in connecting to server"<<std::endl;
        return 1;
    }
    std::cout<<"Connected to server"<<std::endl;
    
    std::string message;
    while (true)
    {
        char buffer[1024];
        std::cout<<"message:  ";
        std::getline(std::cin,message);

        int n =::write(sockfd,message.c_str(),message.size());
        if(n>0)
        {
            int m=::read(sockfd,buffer,sizeof(buffer));
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<"Server response: "<<buffer<<std::endl;

            }
            else
                break;
        }
        else
            break;  
    }
    close(sockfd);
    
    return 0;
}